package com.lei.mingyuemall.product.web;


import com.lei.mingyuemall.product.entity.CategoryEntity;
import com.lei.mingyuemall.product.service.CategoryService;
import com.lei.mingyuemall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;

    @Autowired
    StringRedisTemplate redisTemplate;
    @GetMapping({"/","/index.html","index"})
    public String indexPage(Model model){
        //TODO 1、查出一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<Object, List<Catelog2Vo>>getCatalogJson(){
        Map<Object, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //只要锁的名字一样就是同一把锁
        RLock lock = redisson.getLock("my-lock");
        //2.加锁
//        lock.lock();
        lock.lock(10, TimeUnit.SECONDS);//10s自动解锁，自动解锁的时间一定要大于业务执行的时间
        //lock.lock(10, TimeUnit.SECONDS);在锁时间到了以后，不会自动续期
        try{
            System.out.println("加锁成功，执行业务。。。"+Thread.currentThread().getId());
            Thread.sleep(30000);//阻塞式等待
        }catch (Exception e){

        }
        finally {
            //3.解锁
            System.out.println("释放锁。。"+Thread.currentThread().getId());
            lock.unlock();
        }
        return "hello";
    }

    //保证一定能读到最新数据，修改期间，写锁是一个排他锁（互斥锁，独享）读锁锁一个共享锁
    //写锁没释放就必须等待
    //写 + 读： 等待写锁释放
    //写 + 写： 阻塞方式
    //读 + 写： 等待读锁释放
    //读 + 读： 相当于无锁，并发读，只会在redis中记录好，所有当前读锁。他们都会同时加锁成功
    //只要有写的存在都需要等待
    @ResponseBody
    @GetMapping("/write")
    public String writeValue(){
        String s = "";

        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        try{
            //1.改数据加写锁，读数据加读锁
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue",s);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String readValue(){
        String s = "";
        //加读锁
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.writeLock();
        rLock.lock();
        try{
            s = redisTemplate.opsForValue().get("writeValue");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    /**
     * 放假 锁门
     * 1班没人了
     * 5个班全没人了 才锁大门
     */

    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁都完成
        return "放假了。。。";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();//计数减一
        return id+"班的人走完了。。。";
    }


    /**
     * 车库停车
     * 3车位
     * 信号量也可以限量
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
//        park.acquire();//获取一个信号，获取一个值，占一个车位
        boolean b = park.tryAcquire();
        return "ok=>"+b;
    }

    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();//释放一个车位
        return "ok";
    }


}
